import axios          from 'axios'
import env            from '../config/env'
import Config         from '../config/config'
import Cookies        from 'js-cookie'
import Vue            from 'vue'
import { Message }    from 'iview'



let util = {

};
util.title = function(title) {
  title = title || '购票系统'
  window.document.title = title
};

const ajaxUrl = Config.env === 'development' ?
  'http://www.stu.com/index.php/Api/' :
  Config.env === 'production' ?
  '/index.php/Api/' :
  'http://www.stu.com/index.php/Api/';


// axios.defaults.headers.common['session'] = localStorage.getItem('session');

util.ajax = axios.create({
  baseURL: ajaxUrl,
  timeout: 30000,
  headers: { 'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }
});
// console.log(util.ajax.defaults.headers)
// util.ajax.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

util.getRootPath = function() {
    var pathName = window.location.pathname.substring(1);
    var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
    //return window.location.protocol + '//' + window.location.host + '/'+ webName + '/';
    return window.location.protocol + '//' + window.location.host + '/'+ webName;
   }

util.isEmptyObject = function (obj) {
        for (let i in obj)
            return !1
        return !0
    }
util.getCookieSync = function(key) {
  let objKey = Cookies.get(key)
  return objKey
}

util.getStorageSync = function(key) {
  let storage = localStorage.getItem(key)
  return JSON.parse(storage)
}

util.getStorage = function(key) {
  let storage = localStorage.getItem(key)
  return JSON.parse(storage)
}

util.setStorage = function(data) {
  localStorage.setItem(data.key, JSON.stringify(data.data))
}
util.setStorageSync = function(key, data) {
  localStorage.setItem(key, JSON.stringify(data))
}

util.navigateTo = function(url, query) {
  this.$router.push({path: url, query: query})
}



util.removeStorageSync = function(key) {
  localStorage.removeItem(key)
}

util.cookie =  {
    set: function(name, value) {
      // 缓存过期时间
      let Days = 30
      let exp = new Date()
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
      document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
    },
    get: function(name) {
      let arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
      let reg = arr
      arr = document.cookie.match(reg)
      if (arr) {
        return unescape(arr[2])
      } else {
        return null
      }
    },
    del: function(name) {
      let exp = new Date()
      exp.setTime(exp.getTime() - 1)
      let cval = this.cookie.get(name)
      if (cval != null) {
        document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
      }
    }
}
util.tranferAddress = function (address){

      address.forEach(n => {
        addr.push({
          name: n.name,
          tel: n.phone,
          province: n.province,
          city: n.city,
          county: n.area,
          area_code: n.area_code,
          address: n.address,
          id: n.id,
          is_default: n.is_default == 1?true:false
        })
      })
      return address
},
util.publicid = function(){
  return util.getCookieSync('publicid') || Config.publicid
}
  
    util.ajax.interceptors.request.use(
      config => {
        // console.log(util.getCookieSync('session'))
        if (util.getCookieSync('token')) {
          config.headers.token = util.getCookieSync('token')
        }
        config.headers.publicid = util.getCookieSync('publicid') || Config.publicid
        if(util.getCookieSync('session')) {
          config.headers.session  = util.getCookieSync('session')
        }
         
         
        console.log(config, 'request')
        
        // console.log(config)
        return config
      },
      err => {
        return Promise.reject(err)
      }
    );

    util.ajax.interceptors.response.use(
      config => {
        if(config.data.status < 0) {
          Message.error(config.data.msg);
          Cookies.remove('token')
          Cookies.remove('userInfo')
          Cookies.remove('session')
          localStorage.clear()
          window.location.href = '#/home/login'
        }
        return config
      },
      err => {
        return Promise.reject(err)
      }
    );

util.hasClass = function(el, name) {
  if(el.className.split(' ').indexOf(name) == -1) {
      return false
    } else {
      return true
    }
}    

    export default util;
